﻿using System;

namespace Neoit.Utils.Extensions
{
    /// <summary>
    /// 数学运算扩展
    /// </summary>
    public static class MathExtension
    {
        #region 是否为偶数
        /// <summary>
        /// 是否为偶数
        /// </summary>
        public static bool IsEven(this int value)
        {
            return value % 2 == 0;
        }
        #endregion

        #region int、long 位数
        /// <summary>
        /// 计算位数
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public static int Length(this int v)
        {
            int n = 1;
            if (v > 0)
            {
                while (v > 9)
                {
                    n++;
                    v /= 10;
                }
            }
            else
            {
                while (v < -9)
                {
                    n++;
                    v /= 10;
                }
            }
            return n;
        }
        /// <summary>
        /// 计算位数
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public static int Length(this long v)
        {
            int n = 1;
            if (v > 0)
            {
                while (v > 9)
                {
                    n++;
                    v /= 10;
                }
            }
            else
            {
                while (v < -9)
                {
                    n++;
                    v /= 10;
                }
            }
            return n;
        }
        #endregion

        #region 四舍五入
        /// <summary>
        /// 保留小数-四舍五入
        /// </summary>
        /// <param name="value"></param>
        /// <param name="digits">保留小数位数</param>
        /// <returns></returns>
        public static decimal Round(this decimal value, int digits = 2)
        {
            //而方法Math.Round(2.5) 默认使用 MidpointRounding.ToEven IEEE规范：银行家算法(四舍六入五取偶)
            return Math.Round(value, digits, MidpointRounding.AwayFromZero);
        }
        /// <summary>
        /// 固定保留小数-四舍五入-decimal
        /// </summary>
        /// <param name="value"></param>
        /// <param name="digits">保留小数位数</param>
        /// <returns></returns>
        public static string Fix(this decimal value, int digits = 2)
        {
            return Math.Round(value, digits, MidpointRounding.AwayFromZero).ToString($"f{digits}");
        }
        /// <summary>
        /// 固定保留小数-四舍五入-string
        /// </summary>
        /// <param name="value"></param>
        /// <param name="digits">保留小数位数</param>
        /// <returns></returns>
        public static string Fix(this string value, int digits = 2)
        {
            return Math.Round(decimal.Parse(value), digits, MidpointRounding.AwayFromZero).ToString($"f{digits}");
        }
        #endregion

    }
}
